import { Canvas } from '@react-three/fiber';
import { OrbitControls, useProgress } from '@react-three/drei';
import Map from './Map';
import { Suspense, useEffect, useState } from 'react';
import Loading from './Loading';

function App({ onRegionClick, mapLevels, currentLevel, levelHistory, onDrillDown }) {
	const [loaded, setLoaded] = useState(false);

	// 获取加载进度
	const { progress } = useProgress();

	useEffect(() => {
		if (progress === 100) setLoaded(true);
	}, [progress]);
	
	// 处理区域单击 - 只发送区域名称给Vue父组件，不执行下钻
	const handleRegionClick = (regionName) => {
		// 调用从Vue传递过来的回调函数，传递区域名称给父组件
		if (onRegionClick) {
			onRegionClick(regionName);
		}
	};

	// 处理区域双击 - 执行下钻，由父组件处理
	const handleDrillDown = (regionName) => {
		if (onDrillDown) {
			onDrillDown(regionName);
		}
	};

	// 获取当前地图层级数据
	const currentMapData = mapLevels[currentLevel];

	return (
		<div style={{
			width: '100%',
			height: '100%',
			display: 'flex',
			justifyContent: 'center',
			alignItems: 'center',
			position: 'relative'
		}}>
			{/* 地图层级指示器 */}
			<div style={{
				position: 'absolute',
				top: '20px',
				right: '20px',
				zIndex: 100,
				padding: '10px 15px',
				backgroundColor: 'rgba(0, 0, 0, 0.7)',
				color: 'white',
				border: 'none',
				borderRadius: '4px',
				fontFamily: 'Arial, sans-serif',
				fontSize: '14px',
				display: 'flex',
				flexDirection: 'column',
				alignItems: 'flex-start'
			}}>
				<div style={{ marginBottom: '5px', fontWeight: 'bold' }}>当前层级:</div>
				{/* 显示地图层级路径 */}
				<div style={{ display: 'flex', alignItems: 'center' }}>
					{levelHistory.map((level, index) => (
						<div key={index} style={{ display: 'flex', alignItems: 'center' }}>
							<span>{mapLevels[level].name}</span>
							<span style={{ margin: '0 5px' }}>&gt;</span>
						</div>
					))}
					<span style={{ fontWeight: 'bold' }}>{mapLevels[currentLevel].name}</span>
				</div>
			</div>
			
			<Suspense fallback={<Loading />}>
				{loaded}
				<Canvas 
					style={{ width: '100%', height: '100%' }}
					camera={{ position: [0, 15, 12], fov: 45 }}
				>
					<ambientLight intensity={2} />
					<OrbitControls
						enableZoom={true}
						enablePan={true}
						maxPolarAngle={Math.PI * 0.48}
						minPolarAngle={Math.PI * 0.2}
						maxAzimuthAngle={Math.PI * 0.3}
						minAzimuthAngle={-Math.PI * 0.1}
					/>
					<Map key={currentLevel}
						baseHeight={currentMapData.baseHeight}
						midHeightScale={currentMapData.midHeightScale}
						topHeightScale={currentMapData.topHeightScale}
						values={currentMapData.countValues}
						geoJson={currentMapData.geoJson}
						mapCenter={currentMapData.center}
						distanceFactor={currentMapData.distanceFactor}
						gsapCamera={currentMapData.gsapCamera}
						textYOffset={currentMapData.textYOffset || -0.5}
						onRegionClick={handleRegionClick}
						onRegionDrillDown={handleDrillDown}
					/>
				</Canvas>
			</Suspense>
		</div>
	);
}

export default App;
